package com.jimmy.medical.controller;

import com.jimmy.medical.entity.*;
import com.jimmy.medical.enums.OrderStatusEnum;
import com.jimmy.medical.model.*;
import com.jimmy.medical.service.IFileService;
import com.jimmy.medical.service.IFlowOrderService;
import com.jimmy.medical.service.ISignFlowOrderService;
import com.jimmy.medical.service.IUploadFileService;
import com.jimmy.medical.util.AjaxUtils;
import com.jimmy.medical.util.Func_T;
import com.jimmy.medical.util.Func_T1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/flow")
public class FlowOrderController {
    @Autowired
    @Qualifier("flowOrderService")
    private IFlowOrderService flowOrderService;
    @Autowired
    private IUploadFileService uploadFileService;
    @Autowired
    private IFileService fileService;
    @Autowired
    private ISignFlowOrderService signFlowOrderService;

    /**
     * 返回前端工单数据
     * @param page  分页
     * @param keyword 关键字
     * @param flowOrderType 工单类型
     * @param userId 用户id
     * @param type 1:未完成；2:已完成；3:已作废
     * @return
     */
    @RequestMapping("/list")
    @ResponseBody
    public PageResponseResult<FlowOrder> getFlowOrderList(PageRequestParam page, final String keyword, final Long flowOrderType, final Long userId, final Short type) {
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        return AjaxUtils.processPage(page, sort, new Func_T1<PageRequest, Page<FlowOrder>>() {
            @Override
            public Page<FlowOrder> invoke(PageRequest pageRequest) throws Exception {
                Page<FlowOrder> flowOrderPage = new PageImpl<FlowOrder>(new ArrayList<FlowOrder>());
                if(type != null) {
                    if(type == 1) {
                        flowOrderPage = flowOrderService.findAll(pageRequest, userId, flowOrderType, null, (short)0, null, null, keyword);
                    } else if(type == 2) {
                        flowOrderPage = flowOrderService.findAll(pageRequest, userId, flowOrderType, null,(short)1, null, null, keyword);
                    } else if(type == 3) {
                        flowOrderPage = flowOrderService.findAll(pageRequest, userId, flowOrderType, null,null, OrderStatusEnum.CANCELED.getKey(), null, keyword);
                    }
                }
                for (FlowOrder flowOrder : flowOrderPage.getContent()) {
                    flowOrder.setCountDown(flowOrderService.getCountDown(flowOrder));
                }
                return flowOrderPage;
            }
        });
    }

    @RequestMapping("/detail")
    @ResponseBody
    public AjaxResult<FlowOrder> detail(final Long id) {
        return AjaxUtils.process(new Func_T<FlowOrder>() {
            @Override
            public FlowOrder invoke() throws Exception {
                return flowOrderService.getDetail(id);
            }
        });
    }

    /**
     * 体检和就诊报告
     * @param flowOrderId
     * @return
     */
    @RequestMapping("/orderReport")
    @ResponseBody
    public AjaxResult<OrderReport> orderReport(final Long flowOrderId) {
        return AjaxUtils.process(new Func_T<OrderReport>() {
            @Override
            public OrderReport invoke() throws Exception {
                return flowOrderService.getOrderReport(flowOrderId);
            }
        });
    }

    @RequestMapping("/uploadPhoto")
    @ResponseBody
    public AjaxResult<UploadFile> uploadPhoto(final HttpServletRequest request, HttpServletResponse response) {
        return AjaxUtils.process(new Func_T<UploadFile>() {
            @Override
            public UploadFile invoke() throws Exception {
            String fileName = null;
            String ctxPath = fileService.getServerPath();
            String nowDay = new SimpleDateFormat("yyyyMMdd").format(new Date());
            File file = new File(ctxPath + File.separator + nowDay);
            if (!file.exists()) {
                file.mkdir();// 创建文件根目录
            }
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile mf = multipartRequest.getFile("uploadFile");// 获取上传文件对象
            fileName = UUID.randomUUID().toString() + ".jpg";
            String savePath = file.getPath() + File.separator + fileName;
            File saveFile = new File(savePath);
            FileCopyUtils.copy(mf.getBytes(), saveFile);

            UploadFile image = new UploadFile();
            image.setDisplayName("订单图片");
            image.setFileUrl(nowDay + "/" + fileName);
            uploadFileService.save(image);

            return image;
            }
        });
    }

    /**
     * 获取倒计时
     *
     * @param orderId
     * @return
     */
    @RequestMapping("/countDown")
    @ResponseBody
    public AjaxResult<Long> countDown(final Long orderId) {
        return AjaxUtils.process(new Func_T<Long>() {
            @Override
            public Long invoke() throws Exception {
                return flowOrderService.getCountDown(orderId);
            }
        });
    }

    /**
     * 致电记录保存
     *
     * @return
     * @param: call
     */
    @RequestMapping("/dialRecord")
    @ResponseBody
    public AjaxResult<String> dialRecord(final PhoneCall call) {
        return AjaxUtils.process(new Func_T<String>() {
            @Override
            public String invoke() throws Exception {
                flowOrderService.saveDialInfo(call);
                return "200";
            }
        });
    }

    /**
     * 短信通知
     *
     * @param message
     * @return
     */
    @RequestMapping("/messageRecord")
    @ResponseBody
    public AjaxResult<String> messageRecord(final Message message) {
        return AjaxUtils.process(new Func_T<String>() {
            @Override
            public String invoke() throws Exception {
                flowOrderService.saveMessageInfo(message);
                return "200";
            }
        });
    }

    /**
     * 本工单通话记录
     *
     * @param flowOrderId
     * @return
     */
    @RequestMapping("/phoneCalls")
    @ResponseBody
    public AjaxResult<List<PhoneCall>> phoneCalls(final Long flowOrderId, final String type) {
        return AjaxUtils.process(new Func_T<List<PhoneCall>>() {
            @Override
            public List<PhoneCall> invoke() throws Exception {
                return flowOrderService.getPhoneCallList(flowOrderId, type);
            }
        });
    }

    /**
     * 本工单短信记录
     *
     * @param flowOrderId
     * @return
     */
    @RequestMapping("/messages")
    @ResponseBody
    public AjaxResult<List<Message>> messages(final Long flowOrderId) {
        return AjaxUtils.process(new Func_T<List<Message>>() {
            @Override
            public List<Message> invoke() throws Exception {
                return flowOrderService.getMessageList(flowOrderId);
            }
        });
    }

    /**
     * 退号 - 取消订单，从工单中直接退号时调用，不走流程
     *
     * @param flowOrderId
     * @param userId
     * @param cancelReason
     * @return
     */
    @RequestMapping("/cancelOrder")
    @ResponseBody
    public AjaxResult<String> cancelOrder(final Long flowOrderId, final Long userId, final String cancelReason) {
        return AjaxUtils.process(new Func_T<String>() {
            @Override
            public String invoke() throws Exception {
                flowOrderService.saveCancelOrder(flowOrderId, userId, cancelReason);
                return "200";
            }
        });
    }

    /**
     * 退单 - 取消工单，到中台重新指派服务人员
     *
     * @param flowOrderId
     * @param userId
     * @return
     */
    @RequestMapping("/cancelFlowOrder")
    @ResponseBody
    public AjaxResult<String> cancelFlowOrder(final Long flowOrderId, final Long userId) {
        return AjaxUtils.process(new Func_T<String>() {
            @Override
            public String invoke() throws Exception {
                flowOrderService.saveCancelFlowOrder(flowOrderId, userId);
                return "200";
            }
        });
    }

    /**
     * 改号 - 修改挂号登记信息，从工单中直接改号时调用，不走流程
     *
     * @param info
     * @return
     */
    @RequestMapping("/reSignOrder")
    @ResponseBody
    public AjaxResult<Long> reSignOrder(final SignInfo info) {
        return AjaxUtils.process(new Func_T<Long>() {
            @Override
            public Long invoke() throws Exception {
                return signFlowOrderService.saveSignInfo(info, 3, false);
            }
        });
    }
}
